package com.spider.spiderorderadmin.common.aspect;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.support.spring.PropertyPreFilters;
import com.spider.spiderorderadmin.common.annotation.OperationAspect;
import com.spider.spiderorderadmin.entity.model.ErrorLog;
import com.spider.spiderorderadmin.entity.model.OperationRecord;
import com.spider.spiderorderadmin.mapper.ErrorLogMapper;
import com.spider.spiderorderadmin.mapper.OperationRecordMapper;
import com.spider.spiderorderadmin.utils.DateUtils;
import com.spider.spiderorderadmin.utils.IpAddrUtils;
import com.spider.spiderorderadmin.utils.ServletUtils;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.NamedThreadLocal;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Collection;
import java.util.Map;


/**
 * @author xiong.bo
 * @version 1.0
 * @date 2021/1/7 14:38
 */

@Aspect
@Component
@Log4j2
public class OperationLogAspect {

    @Autowired
    private OperationRecordMapper operationRecordMapper;
    @Autowired
    private ErrorLogMapper errorLogMapper;

    /**
     * 排除敏感属性字段
     */
    public static final String[] EXCLUDE_PROPERTIES = {"password", "oldPassword", "newPassword", "confirmPassword"};

    /**
     * 计算操作消耗时间
     */
    private static final ThreadLocal<Long> TIME_THREADLOCAL = new NamedThreadLocal<>("Cost Time");

    /**
     * 处理请求前执行
     */
    @Before(value = "@annotation(controllerLog)")
    public void boBefore(JoinPoint joinPoint, OperationAspect controllerLog) {
        TIME_THREADLOCAL.set(System.currentTimeMillis());
    }

    /**
     * 拦截异常操作
     *
     * @param joinPoint 切点
     * @param e         异常
     */
    @AfterThrowing(value = "@annotation(controllerLog)", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, OperationAspect controllerLog, Exception e) {
        handleLog(joinPoint, controllerLog, e, null);
    }

    protected void handleLog(final JoinPoint joinPoint, OperationAspect controllerLog, final Exception e, Object jsonResult) {
        try {

            String className = joinPoint.getTarget().getClass().getName();
            String methodName = joinPoint.getSignature().getName();

            HttpServletRequest request = ServletUtils.getRequest();

            String ipAddr = IpAddrUtils.getIpAddr(request);
            Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            String requestURI = request.getRequestURI();
            Long costTime = System.currentTimeMillis() - TIME_THREADLOCAL.get();

            System.out.println("方法名称：" + className + "." + methodName + "()");

            ErrorLog errorLog = new ErrorLog();
            errorLog.setUsername(String.valueOf(principal));
            errorLog.setRequestMethod(request.getMethod());
            errorLog.setAccessPath(requestURI);
            errorLog.setRequestParam(request.getQueryString());
            errorLog.setRequestBody(null);
            errorLog.setResponseDesc(e.toString());
            errorLog.setAccessIp(ipAddr);
            errorLog.setCostTime(costTime);
            errorLog.setCreateTime(DateUtils.getCurrentTimestamp());
            //记录请求入参和响应结果
            getControllerMethodDescription(joinPoint, errorLog, jsonResult);
            if (e != null) {
                //记录错误日志
                errorLog.setResponseDesc(StringUtils.substring(e.toString(), 0, 2000));
            }

            errorLogMapper.insert(errorLog);

        } catch (Exception exp) {
            // 记录本地异常日志
            log.error("异常信息:{}", exp.getMessage());
            exp.printStackTrace();
        } finally {
            TIME_THREADLOCAL.remove();
        }
    }

    @Pointcut("@annotation(com.spider.spiderorderadmin.common.annotation.OperationAspect)")
    public void operationPointCut() {
    }


    @Around("operationPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        //执行方法
        Object result = point.proceed();
        //保存日志
        saveOperationLog(point);
        return result;
    }


    /**
     * 保存操作记录
     * 使用了 @Around,是等切面方法执行成功后，才进入下列方法
     */
    private void saveOperationLog(ProceedingJoinPoint joinPoint) {

        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        OperationAspect operationLog = signature.getMethod().getAnnotation(OperationAspect.class);

        OperationRecord operation = new OperationRecord();
        // 请求的参数
        try {
            HttpServletRequest request = ServletUtils.getRequest();

            String ipAddr = IpAddrUtils.getIpAddr(request);
            Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

            operation.setUsername(String.valueOf(principal));
            operation.setAccessPath(operationLog.accessPath());
            operation.setAccessDesc(operationLog.accessDesc());
            operation.setAccessIp(ipAddr);
            operation.setCreateTime(DateUtils.getCurrentTimestamp());

            operationRecordMapper.insert(operation);

        } catch (Exception e) {
            log.error("操作日志切面异常：" + e);
        }
    }

    /**
     * 获取注解中对方法的描述信息 用于Controller层注解
     *
     * @param joinPoint  连接点对象
     * @param errorLog   错误日志
     * @param jsonResult 请求返回的对象
     */
    public void getControllerMethodDescription(JoinPoint joinPoint, ErrorLog errorLog, Object jsonResult) {
        // 获取参数的信息，传入到数据库中。
        setRequestValue(joinPoint, errorLog, null);
        // 是否需要保存response，参数和值
        if (!ObjectUtils.isEmpty(jsonResult)) {
            errorLog.setResponseDesc(StringUtils.substring(JSONObject.toJSONString(jsonResult), 0, 2000));
        }
    }

    /**
     * 获取请求的参数，放到ErrorLog中
     *
     * @param errorLog 操作日志
     * @throws Exception 异常
     */
    private void setRequestValue(JoinPoint joinPoint, ErrorLog errorLog, String[] excludeParamNames) {
        Map<String, String[]> map = ServletUtils.getRequest().getParameterMap();
        if (!ObjectUtils.isEmpty(map)) {
            String params = JSONObject.toJSONString(map, excludePropertyPreFilter(excludeParamNames));
            errorLog.setRequestParam(StringUtils.substring(params, 0, 2000));
        } else {
            Object args = joinPoint.getArgs();
            if (!ObjectUtils.isEmpty(args)) {
                String params = argsArrayToString(joinPoint.getArgs(), excludeParamNames);
                errorLog.setRequestParam(StringUtils.substring(params, 0, 2000));
            }
        }
    }


    /**
     * 忽略敏感属性
     */
    public PropertyPreFilters.MySimplePropertyPreFilter excludePropertyPreFilter(String[] excludeParamNames) {
        return new PropertyPreFilters().addFilter().addExcludes(ArrayUtils.addAll(EXCLUDE_PROPERTIES, excludeParamNames));
    }

    /**
     * 参数拼装
     */
    private String argsArrayToString(Object[] paramsArray, String[] excludeParamNames) {
        String params = "";
        if (paramsArray != null && paramsArray.length > 0) {
            for (Object o : paramsArray) {
                if (!ObjectUtils.isEmpty(o) && !isFilterObject(o)) {
                    try {
                        Object jsonObj = JSONObject.toJSONString(o, excludePropertyPreFilter(excludeParamNames));
                        params += jsonObj.toString() + " ";
                    } catch (Exception e) {
                        log.error("argsArrayToString error，参数拼接异常：", e);
                    }
                }
            }
        }
        return params.trim();
    }

    /**
     * 判断是否需要过滤的对象。
     * （这里是过滤文件等大内容）
     *
     * @param o 对象信息。
     * @return 如果是需要过滤的对象，则返回true；否则返回false。
     */
    @SuppressWarnings("rawtypes")
    public boolean isFilterObject(final Object o) {
        Class<?> clazz = o.getClass();
        if (clazz.isArray()) {
            return clazz.getComponentType().isAssignableFrom(MultipartFile.class);
        } else if (Collection.class.isAssignableFrom(clazz)) {
            Collection collection = (Collection) o;
            for (Object value : collection) {
                return value instanceof MultipartFile;
            }
        } else if (Map.class.isAssignableFrom(clazz)) {
            Map map = (Map) o;
            for (Object value : map.entrySet()) {
                Map.Entry entry = (Map.Entry) value;
                return entry.getValue() instanceof MultipartFile;
            }
        }
        return o instanceof MultipartFile || o instanceof HttpServletRequest || o instanceof HttpServletResponse
                || o instanceof BindingResult;
    }

}
